package com.trigsoft.applist;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.content.Context;
import android.os.SystemClock;

import com.trigsoft.utils.PrefUtil;
import com.trigsoft.utils.ProcessUtils;

public class AppStatist
{

	public static class DateUtil
	{
		private static final SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
		private static final SimpleDateFormat y = new SimpleDateFormat("yyyy");
		private static final String year = y.format(new Date());

		public static String fromDate(Date d)
		{
			return df.format(d);
		}

		public static Date getLastTime(Date lastTime)
		{
			Date bootTime = new Date(new Date().getTime() - SystemClock.elapsedRealtime());
			if (lastTime != null && lastTime.after(bootTime))
				return lastTime;
			return bootTime;
		}

		public static String getNewLastTime(String d)
		{
			if (d == null)
				return d;
			return year + "-" + d;
		}

		public static Date toDate(String s)
		{
			try
			{
				return df.parse(year + "-" + s);
			} catch (ParseException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
		}

		public static Date toDateFromPref(String s)
		{
			try
			{
				return df.parse(s);
			} catch (ParseException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
		}
	}

	public static void getStatistics(Context context)
	{
		// TODO Auto-generated method stub
		Date lastTime = DateUtil.getLastTime((PrefUtil.getTime(context)));
		//Log.d("test", lastTime.toLocaleString());

		Process process;
		try
		{
			process = Runtime.getRuntime().exec("logcat -d -v time ActivityManager:I *:S");

			BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()), 1024);

			String newLastTime = null;
			boolean later = false;
			String line = "";
			/*Check if the first line is after the last check time*/
			for (line = bufferedReader.readLine(); line != null; line = bufferedReader.readLine())
			{
				if (!line.contains("Starting: Intent"))
					continue;
				String time = line.substring(0, 18);
				if (DateUtil.toDate(time).after(lastTime))
				{
					later = true;
					break;
				}
			}

			/* Here I know all info I found should be put into DB */
			if (later)
			{
				for (; line != null; line = bufferedReader.readLine())
				{
					/* Step 1: Process all lines with "Starting: Intent" */
					if (!line.contains("Starting: Intent"))
					{
						//Log.d("test", line);
						continue;
					}

					/* Step 2: Process the line that matches the format
					 * 07-02 15:47:46.103 I/ActivityManager(  161): Starting: Intent { cmp=com.trigsoft.applist/.StatisticsAct } from pid 1717
					 */
					Pattern p = Pattern.compile("cmp=([a-zA-Z0-9\\.]+)/([a-zA-Z0-9\\.]+) .+ (\\S+)$");
					Matcher m = p.matcher(line);

					if (m.find())
					{
						/* Step 3: Get the package, class, and process id */
						String pkg = m.group(1);
						//String name = m.group(2);
						String pid = m.group(3);
						//Log.d("test", line);
						//Log.d("test", pkg);
						/* Step 4: Igore if it is started by itself */
						if (!ProcessUtils.startedBySelf(pid, pkg))
							/* Step 5: Update the count */
							DBHelper.updateCount(pkg);
						/* Step 6: Save the time */
						newLastTime = line.substring(0, 18);
						;
					}

				}

			}
			PrefUtil.updateTime(DateUtil.getNewLastTime(newLastTime), context);
		} catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
